package com.gitee.jwds666.fs.utils;


import org.springframework.util.DigestUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.*;

public class FileUtils {



    public static List<File> getFileList(String path){
        return getFileList(new File(path));
    }

    public static List<File> getFileList(File file){
        File[] files = file.listFiles();
        if (files == null)return Collections.emptyList();
        return Arrays.asList(files);
    }

    public static Date getFileUpdateTime(File file){
        BasicFileAttributes attr = null;
        try {
            Path path =  file.toPath();
            attr = Files.readAttributes(path, BasicFileAttributes.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建时间
        Instant instant = attr.creationTime().toInstant();
        return new Date(instant.getEpochSecond()*1000);
    }


    public static boolean ensurePathCorrect(String path){
        return path!= null && path.length() != 0 &&  path.indexOf("./") == -1 && path.indexOf(".\\")==-1 && path.indexOf(":")==-1;
    }
    public static boolean ensureFilenameCorrect(String filename){
        return filename!= null
                && filename.length() != 0
                && filename.indexOf("/") == -1
                && filename.indexOf("\\")==-1
                && filename.indexOf(":")==-1
                && filename.indexOf("*")==-1
                && filename.indexOf("?")==-1
                && filename.indexOf("\"")==-1
                && filename.indexOf("<")==-1
                && filename.indexOf(">")==-1
                && filename.indexOf("|")==-1;
    }

    public static String getFileSuffix(File file){
        if (file.isDirectory()){
            return "";
        }
        String fileName = file.getName();
        int index = fileName.lastIndexOf(".");

        return index == -1 ? "" : fileName.substring(index);
    }

    /**
     * 将文件进行MD5加密
     * @param fis
     * @return
     */
    public static final String getFileMD5String(InputStream fis) {
        String md5Result = "";
        try {
            fis.mark(0);
            md5Result = DigestUtils.md5DigestAsHex(fis);
            fis.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return md5Result;
    }

    public static ByteArrayInputStream genericBufferedStream(InputStream inputStream) throws IOException {
        try (InputStream is = inputStream){
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            ByteArrayInputStream res = new ByteArrayInputStream(bytes);
            return res;
        }

    }

}
